package model;

import java.io.*;
import java.util.*;

public class GroupManager {
	public final int MAX_GROUP_SIZE;
    public final int TOTAL_GROUPS;
    private Map<Integer, List<Student>> groups = new HashMap<>();
    private Map<String, Student> validStudents = new HashMap<>();
    private String resultFilePath;

    public GroupManager(String studentFilePath, String resultFilePath, int maxGroupSize, int totalGroups) throws IOException {
        this.resultFilePath = resultFilePath;
        this.MAX_GROUP_SIZE = maxGroupSize;
        this.TOTAL_GROUPS = totalGroups;

        // 初始化分组
        for (int i = 1; i <= TOTAL_GROUPS; i++) {
            groups.put(i, new ArrayList<>());
        }

        loadValidStudents(studentFilePath);
        loadGroupResults();
    }

    // 加载有效学生列表
    private void loadValidStudents(String filePath) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "UTF-8"));
        String line;
        while ((line = reader.readLine()) != null) {
            String[] parts = line.trim().split(",");
            if (parts.length == 2) {
                validStudents.put(parts[1], new Student(parts[0], parts[1]));
            }
        }
        reader.close();
    }

    // 加载已分组结果
    private void loadGroupResults() throws IOException {
        File file = new File(resultFilePath);
        if (!file.exists()) {
            // 如果文件不存在，保持分组为空（已在构造函数中初始化）
            return;
        }
        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(resultFilePath), "UTF-8"));
        String line;
        while ((line = reader.readLine()) != null) {
            if (line.trim().isEmpty()) continue;
            String[] groupInfo = line.split(":");
            int groupNumber = Integer.parseInt(groupInfo[0].replace("组", "").trim());
            List<Student> groupMembers = new ArrayList<>();
            if (groupInfo.length > 1) {
                String[] students = groupInfo[1].split(";");
                for (String studentStr : students) {
                    String[] studentInfo = studentStr.split(",");
                    if (studentInfo.length == 2) {
                        groupMembers.add(new Student(studentInfo[0], studentInfo[1]));
                    }
                }
            }
            groups.put(groupNumber, groupMembers);
        }
        reader.close();
    }

    // 验证学生信息
    public boolean isValidStudent(String name, String studentId) {
        Student student = validStudents.get(studentId);
        return student != null && student.getName().equals(name);
    }

    // 检查学生是否已分组
    public boolean isStudentGrouped(String studentId) {
        for (List<Student> group : groups.values()) {
            for (Student student : group) {
                if (student.getStudentId().equals(studentId)) {
                    return true;
                }
            }
        }
        return false;
    }

    // 将学生加入随机组
    public void addStudentToGroup(Student student) throws IOException {
        // 找到人数未满的组
        List<Integer> availableGroups = new ArrayList<>();
        for (int i = 1; i <= TOTAL_GROUPS; i++) {
            List<Student> group = groups.get(i);
            if (group.size() < MAX_GROUP_SIZE) {
                availableGroups.add(i);
            }
        }
        if (availableGroups.isEmpty()) {
            throw new RuntimeException("所有小组都已满员！");
        }
        // 随机分配到一个组
        Collections.shuffle(availableGroups);
        int assignedGroup = availableGroups.get(0);
        groups.get(assignedGroup).add(student);
        saveGroupResults();
    }

    // 保存分组结果到文件
    public void saveGroupResults() throws IOException {
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(resultFilePath), "UTF-8"));
        for (int i = 1; i <= TOTAL_GROUPS; i++) {
            List<Student> group = groups.get(i);
            writer.write(i + "组:");
            for (int j = 0; j < group.size(); j++) {
                Student student = group.get(j);
                writer.write(student.getName() + "," + student.getStudentId());
                if (j != group.size() - 1) {
                    writer.write(";");
                }
            }
            writer.newLine();
        }
        writer.close();
    }

    // 获取所有分组信息
    public Map<Integer, List<Student>> getGroups() {
        return groups;
    }

    // 从组中移除学生
    public void removeStudentFromGroup(String studentId) {
        for (List<Student> group : groups.values()) {
            group.removeIf(student -> student.getStudentId().equals(studentId));
        }
        try {
            saveGroupResults();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 将学生添加到指定组
    public void addStudentToSpecificGroup(Student student, int groupNumber) {
        List<Student> group = groups.get(groupNumber);
        if (group.size() < MAX_GROUP_SIZE) {
            group.add(student);
            try {
                saveGroupResults();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            throw new RuntimeException("该组已满员！");
        }
    }
}
